package cn.bookcycle.panda.user.controller;

import cn.bookcycle.panda.user.util.Dao;
import cn.bookcycle.panda.user.pojo.DO.AuthsDO;
import cn.bookcycle.panda.user.service.AuthsService;

import cn.bookcycle.panda.user.util.PatternUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.HttpClientErrorException;

import java.util.List;


@RequestMapping("/auths")
@RestController
public class AuthsController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final String TELEPHONE="telephone";
    private final String EMAIL="email";
    private final String ACCOUNT="account";
    private final String WECHAT="wechat";

    @Autowired
    AuthsService authsService;
    @Autowired
    Dao<AuthsDO> authsDODao;
    /**
     * 密码、标识查找账号
     * @param identifier
     * @param credential
     * @param type
     * @return
     */
    @RequestMapping(value = "/getAuths/{identifier}/{credential}/{type}",method = RequestMethod.GET)
    public ResponseEntity<AuthsDO> getAuths(@PathVariable("identifier") String identifier,
                                                @PathVariable("credential") String credential,
                                                @PathVariable("type")String type){
        if(credential==null||identifier==null||"".equals(identifier)||"".equals(credential)){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
        }
        try {
            AuthsDO authsDO = authsService.getAuths(identifier,credential,type);
            if (authsDO == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
            }else {
                return ResponseEntity.status(HttpStatus.FOUND).body(authsDO);
            }
        }catch (Exception e){
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    /**
     * 用Id查找账号
     * @param authsId
     * @return
     */
    @RequestMapping(value = "/getAuthsById/{AuthsId}",method = RequestMethod.GET)
    public ResponseEntity<AuthsDO> getAuthsById(@PathVariable("AuthsId")String authsId){
        try {
            AuthsDO authsDO = authsService.getAuthsById(authsId);
            if (authsDO == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
            }else {
                return ResponseEntity.status(HttpStatus.FOUND).body(authsDO);
            }
        }catch (Exception e){
            logger.error(e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }

    }

    /**
     *
     * @param identifier
     * @param credential
     * @param type
     * @return
     */
    @RequestMapping(value = "/saveAuths",method = RequestMethod.POST)
    public ResponseEntity<Void> saveAuths(@RequestParam("id")String id,
                                          @RequestParam("identifier")String identifier,
                                          @RequestParam("credential")String credential,
                                          @RequestParam("type")String type){
        if(credential == null || identifier == null || "".equals(identifier)||"".equals(credential)){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
        }
        if(!new PatternUtil().checkCredential(credential)){
            return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body(null);
        }

        if(type.equals(this.TELEPHONE)&&!new PatternUtil().checkTelephone(identifier)){
            return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body(null);
        }else if(type.equals(this.EMAIL)&&!new PatternUtil().checkEmail(identifier)){
            return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body(null);
        }else if (type.equals(this.ACCOUNT)&&!new PatternUtil().checkAccount(identifier)){
            return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body(null);
        }

        if (this.isIdentifierExist(identifier,type)) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body(null);
        }

        try {
            AuthsDO authsDO=new AuthsDO();
            authsDO.setId(id);
            authsDO.setIdentifier(identifier);
            authsDO.setCredential(credential);
            authsDO.setType(type);
            authsDO.setUserId(id);
            authsService.saveAuths(authsDO);
            return ResponseEntity.status(HttpStatus.CREATED).body(null);
        }catch (HttpClientErrorException e){
            logger.error(e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    /**
     * 更新账号
     * @param
     * @return
     */
    @RequestMapping(value = "/updateAuths",method = RequestMethod.PUT)
    public ResponseEntity<Void> updateAuths(@RequestBody AuthsDO authsDO){
        try {
            if(authsService.updateAuths(authsDO)){
                return ResponseEntity.status(HttpStatus.OK).body(null);
            }else {
                return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(null);
            }
        }catch (Exception e){
            logger.warn(e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    /**
     * 删除账号
     * @param
     * @return
     */
    @RequestMapping(value = "/removeAuths",method = RequestMethod.PUT)
    public ResponseEntity<Void> removeAuths(@RequestBody AuthsDO authsDO){
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }

    /**
     *
     * @return
     */
    @RequestMapping(value = "/listAuths",method = RequestMethod.POST)
    public ResponseEntity<List> listUsers(@RequestBody AuthsDO authsDO){
        try{
            List userDOList=authsService.listAuths(authsDO);
            return ResponseEntity.status(HttpStatus.FOUND).body(userDOList);
        }catch (HttpClientErrorException e){
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }


    /**
     * 判断账号是否已经被注册，注册的辅助功能
     * @param identifier
     * @return true-账号已经存在 false-账号尚未被注册
     */
    private boolean isIdentifierExist(String identifier,String type) {
        AuthsDO auths = new AuthsDO();
        auths.setType(type);
        auths.setIdentifier(identifier);
        String result = authsDODao.daoMethod("auths","find",auths);
        if (result==null) {
            return false;
        } else {
            return true;
        }
    }
}
